package com.example.homework

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.homework.model.User
import com.bumptech.glide.Glide

class RankAdapter : RecyclerView.Adapter<RankAdapter.RankViewHolder>() {

    private var users = listOf<User>()

    fun updateData(newUsers: List<User>) {
        users = newUsers
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RankViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_rank, parent, false)
        return RankViewHolder(view)
    }

    override fun onBindViewHolder(holder: RankViewHolder, position: Int) {
        val user = users[position]
        holder.bind(user, position + 1) // 传递名次（从1开始）
    }

    override fun getItemCount() = users.size

    class RankViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val ivAvatar: ImageView = itemView.findViewById(R.id.iv_avatar)
        private val tvUsername: TextView = itemView.findViewById(R.id.tv_username)
        private val tvAccount: TextView = itemView.findViewById(R.id.tv_account)
        private val tvHighScore: TextView = itemView.findViewById(R.id.tv_high_score)
        private val tvRank: TextView = itemView.findViewById(R.id.tv_rank) // 新增名次显示的TextView

        fun bind(user: User, rank: Int) { // 修改bind方法，添加rank参数
            tvUsername.text = user.username
            tvAccount.text = user.account
            tvHighScore.text = "最高分: ${user.highScore}"
            tvRank.text = "$rank" // 设置名次

            // 加载头像
            if (user.avatar.isNotEmpty()) {
                Glide.with(itemView.context).load(user.avatar).into(ivAvatar)
            } else {
                ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder)
            }
        }
    }
}